// create 页面复用逻辑
import { computed, unref, ref, reactive } from 'vue'
// import router from '@/router'
// import { useRouter } from 'vue-router'
import { FormInstance } from 'element-plus'
import { RouteLocationNormalizedLoaded } from 'vue-router'
import { useEmitt } from '@/hooks/web/useEmitt'
import { useTagsViewStore } from '@/store/modules/tagsView'

interface Option {
  instance: any
  route: RouteLocationNormalizedLoaded
  preSave?: Fn //保存前格式化数据
  createApi?: Fn // 创建api
  updateApi: Fn // update api
  afterSave: Fn // 保存后回调事件
}

const isViewsActive = (fullPath) => {
  // console.log(router.currentRoute.value)
  // console.log(useTagsViewStore().getSelectedTagFullPath)
  return fullPath === useTagsViewStore().getSelectedTagFullPath
}

export const useCreate = (option?: Option) => {
  const loading = ref(false)
  const elFormRef = ref<FormInstance>()

  const colProps = reactive({
    xs: 24,
    sm: 12,
    md: 8,
    xl: 6
  })

  const { emitter } = useEmitt()

  const selectConditions = computed(() => {
    return {
      pageIndex: -1,
      order: 'sequence',
      disabled: openMode.value === 'CREATE' ? 'N' : ''
    }
  })

  // 一个计算属性 ref
  const openMode = computed((): 'CREATE' | 'UPDATE' => {
    return option!.route!.params!.id ? 'UPDATE' : 'CREATE'
  })

  const reset = () => {
    const form = unref(elFormRef)
    form?.resetFields()
  }

  const save = async () => {
    const form = unref(elFormRef)
    await form?.validate(async (isValid) => {
      if (isValid) {
        loading.value = true
        if (option?.preSave) {
          option.preSave()
        }
        const res = await (openMode.value === 'CREATE'
          ? option?.createApi!(option.instance)
          : option?.updateApi(option.instance.id!, option.instance)
        ).finally(() => {
          loading.value = false
        })
        if (res) {
          postSave()
        }
      }
    })
  }

  const postSave = () => {
    emitter.emit('getList', 'add')

    // console.log('emit', 'getList', option!.route!.fullPath)

    // TODO 保存后关闭
    emitter.emit('closeCurrentTag')
    if (option?.afterSave) {
      option.afterSave()
    }
  }

  return {
    openMode,
    loading,
    elFormRef,
    colProps,
    selectConditions,
    reset,
    save,
    postSave,
    isViewsActive
  }
}
